<?php

namespace App\Console\Commands;

use App\Common\Constant\Params;
use App\Models\Merchant;
use App\Models\OldOrder;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderGoods;
use App\Models\OrderOffer;
use App\Models\OrderStatus;
use App\Services\IStorageService;
use DB;
use Illuminate\Console\Command;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\Collection;
use Log;

class repairOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:repair-order {offset=0}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '修复订单';

    private $exceptionHandler;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(ExceptionHandler $exceptionHandler)
    {
        parent::__construct();

        $this->exceptionHandler = $exceptionHandler;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $bar = $this->output->createProgressBar(Order::count());
        $offset = $this->argument('offset');

        Order::orderBy('id')->chunk(100, function ($orders) use (&$bar,&$offset){
            foreach ($orders as $model) {
                if ($bar->getProgress() < $offset){
                    $this->line("\tOrder [{$model->id}] skip");
                    $bar->advance();
                    continue;
                }

                DB::beginTransaction();
                try{
                    $detail = $model->detail;
                    $ret = $detail->update([
                        'customer_area'=>$detail->customer_area_text
                    ]);
                    if (!$ret){
                        throw new \Exception('detail customer_area update fail');
                    }

                    DB::commit();
                    $this->info("\tOrder [{$model->id}] success");
                }catch (\Exception $e){
                    DB::rollBack();
                    $this->error("\tOrder [{$model->id}] fail\nerror: ".$e->getMessage()." in ".$e->getFile()."[".$e->getLine()."]\n");
                    Log::error("\tOrder [{$model->id}] fail\nerror: ".$e->getMessage()." in ".$e->getFile()."[".$e->getLine()."]\n");
                    $this->exceptionHandler->report($e);
                }

                $bar->advance();
            }
        });

        $bar->finish();

    }
}
